package com.xiaobaibai.security.token.config;

import com.xiaobaibai.security.common.HttpFailureHandler;
import com.xiaobaibai.security.token.filter.JwtAuthenticationFilter;
import com.xiaobaibai.security.token.handler.TokenSuccessHandler;
import com.xiaobaibai.security.token.provider.JwtAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.access.channel.ChannelProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter;

//@Configuration
public class TokenConfig <T extends TokenConfig<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B> {

    private JwtAuthenticationFilter jwtAuthenticationFilter;

    private JwtAuthenticationProvider jwtAuthenticationProvider;

    public TokenConfig(){
        jwtAuthenticationFilter=new JwtAuthenticationFilter();
    }

    @Override
    public void configure(B http) throws Exception {
        jwtAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        jwtAuthenticationFilter.setAuthenticationFailureHandler(new HttpFailureHandler());

        JwtAuthenticationFilter filter = postProcess(jwtAuthenticationFilter);

        http.authenticationProvider(jwtAuthenticationProvider)
                .addFilterAfter(filter, UsernamePasswordAuthenticationFilter.class);
    }

    public TokenConfig<T, B> tokenSuccessHandler(AuthenticationSuccessHandler successHandler){
        jwtAuthenticationFilter.setAuthenticationSuccessHandler(successHandler);
        return this;
    }

    public TokenConfig<T, B> setJwtAuthenticationProvider(JwtAuthenticationProvider jwtAuthenticationProvider) {
        this.jwtAuthenticationProvider = jwtAuthenticationProvider;
        return this;
    }
}
